import flask, json
from flask import request,jsonify
import time
from send_mail import get_date,send_mail
import logging
from logging.handlers import RotatingFileHandler
try:
    from make_jmx_script import writeXML
except:
    pass
import os
from subprocess import Popen, PIPE
from config import Config
#日至等级的设置
logging.basicConfig(level=logging.DEBUG)
#创建日志记录器，指明日志保存路径,每个日志的大小，保存日志的上限
file_log_handler = RotatingFileHandler('logs/flask_logs',maxBytes=1024*1024,backupCount=10)
#设置日志的格式           日志等级     日志信息文件名   行数        日志信息
formatter=logging.Formatter('%(levelname)s %(filename)s %(lineno)d %(message)s')
#将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)
#为全局的日志工具对象添加日志记录器
logging.getLogger().addHandler(file_log_handler)

'''
flask： web框架，通过flask提供的装饰器@server.route()将普通函数转换为服务
登录接口，需要传url、username、passwd
'''
# 创建一个服务，把当前这个python文件当做一个服务
server = flask.Flask(__name__)
import pymysql
import config
host=Config.host
user=Config.user
password=Config.password
db=Config.db
port=Config.port


def insert_db(job_name, job_build_number ,job_build_timestamp,status,all,fail_num,version,real_version,sonar_bugs,sonar_test_rate,sonar_report,sonar_bugs_total,openapi_report,col_id):
    try:
        connection = pymysql.connect(host=host, user=user,
                                     password=password, db=db, port=port, charset='UTF8')
        cursor = connection.cursor()
        if not version:
            version='R16.9x' if '_x' in job_name else 'R16.4x'
        if not real_version:
            real_version='R16.9x' if '_x' in job_name else 'R16.4x'
        if not sonar_bugs_total:
            sonar_bugs_total=""
        print(job_name,job_name.split('_')[0]+'流水线','R16.4x', job_build_number,1 if status=='SUCCESS' else 0, job_build_timestamp)
        cmd = "insert ignore into jenkins_job values(0, '{}', '{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}');".format(
            job_name.split('_')[0].upper(),job_name,job_name.split('_')[0]+'流水线',version, job_build_number,
            1 if status in ('SUCCESS','1',1) else 0, int(job_build_timestamp),all,fail_num,real_version,
            sonar_bugs_total,sonar_bugs, sonar_test_rate,sonar_report,openapi_report,col_id
        )
        print(cmd)
        cursor.execute(cmd.encode('utf8'))
        connection.commit()
        connection.close()
    except Exception as e:
        print(e)
        pass


def insert_yapi(job_name):
    try:
        connection = pymysql.connect(host=host, user=user,
                                     password=password, db=db, port=port, charset='UTF8')
        cursor = connection.cursor()
        cmd = "insert ignore into jenkins_job values(0, '{}','{}');".format(
            job_name,job_name.split('_')[0]+'流水线'
        )
        print(cmd)
        cursor.execute(cmd.encode('utf8'))
        connection.commit()
        connection.close()
    except Exception as e:
        print(e)
        pass


# server.config['JSON_AS_ASCII'] = False
# @server.route()可以将普通函数转变为服务 登录接口的路径、请求方式
@server.route('/add_jenkins_data', methods=['post'])
def add_jenkins_data():
    # 获取通过url请求传参的数据
    try:
        logging.debug(request)
        data=request.get_json()
        logging.debug('data":{}'.format(data))
        print(data)
        job_name = str(data.get('job_name')).strip()
        job_build_number = str(data.get('job_build_number')).strip()
        status=str(data.get('status')).strip()
        job_build_timestamp=str(data.get('job_build_timestamp')).strip()
        all = str(data.get('all')).strip()
        fail_num = str(data.get('fail_num')).strip()
        version = str(data.get('version','NULL'))
        real_version = str(data.get('real_version','NULL'))
        sonar_report=str(data.get('sonar_report','NULL'))
        openapi_report = str(data.get('openapi_report', 'NULL'))
        col_id=str(data.get('col_id', 'NULL'))

        job_build_number=int(job_build_number)
        all=int(all)
        fail_num=int(fail_num)
        sonar_bugs = str(data.get('sonar_bugs', 'NULL' ))
        sonar_bugs_total= str(data.get('sonar_bugs_total', sonar_bugs))
        sonar_test_rate = str(data.get('sonar_test_rate', 'NaN'))
    except Exception as e:
        return jsonify({'code': 400, 'message': str(e)})
    # job_build_date = request.values.get('job_build_date')
    try:
        if ' ' in job_build_timestamp:
            job_build_timestamp = job_build_timestamp.split(' ')
            res = ' '.join(job_build_timestamp[0:2])
            timeArray = time.strptime(res, "%Y-%m-%d %H:%M:%S")
            print(res)
            timeStamp = int(time.mktime(timeArray))
            print(timeStamp)
        else:
            timeStamp=job_build_timestamp
        insert_db(job_name, job_build_number ,timeStamp,status,all,fail_num,version,real_version,sonar_bugs,sonar_test_rate,sonar_report,sonar_bugs_total,openapi_report,col_id)
        return jsonify({'code': 200})
    except Exception as e:
        return jsonify({'code': 400, 'message': str(e)})

@server.route('/get_jenkins_data', methods=[ 'post'])
def get_jenkins_data():
    # 获取通过url请求传参的数据
    data=request.get_json()
    print(data)
    days = data.get('days','7')
    receiver = data.get('receiver','qiuting@uyunsoft.cn')
    try:
        file_name = get_date(days)
        send_mail(receiver, file_name,days)
        return jsonify({'code': 200})
    except Exception as e:
        return jsonify({'code': 400, 'message': str(e)})


@server.route('/get_jmx_script', methods=['post'])
def get_jmx_script():
    # 获取通过url请求传参的数据
    try:
        data = request.get_json()
        print(data)
        prod_id = data.get('prod_id')
        col_id = data.get('col_id')
        receiver = data.get('receiver')
        ip_address = data.get('ip_address')
        apikey = data.get('apikey')
        port = data.get('port')
        test_protocol = data.get('test_protocol')
        prod_name=writeXML(prod_id,col_id,ip_address,apikey,port,test_protocol)
        logging.debug(prod_name)
        send_mail(receiver,prod_name,None,data='文件见附件！',header="yapi转换jmeter结果",report_name=prod_name)
        return jsonify({'code': 200})
    except Exception as e:
        return jsonify({'code': 400, 'message': str(e)})

@server.route('/test_server', methods=['get'])
def test_server():
    # 获取通过url请求传参的数据
    try:
        return jsonify({'code': 200})
    except Exception as e:
        return jsonify({'code': 400, 'message': str(e)})

if __name__ == '__main__':
    server.run(debug=True, port=8888, host='0.0.0.0')  # 指定端口、host,0.0.0.0代表不管几个网卡，任何ip都可以访问